package com.senlingspace.payment.douyin.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.senlingspace.common.core.domain.AjaxResult;
import com.senlingspace.common.enums.OrderSource;
import com.senlingspace.common.exception.ServiceException;
import com.senlingspace.common.utils.StringUtils;
import com.senlingspace.framework.security.context.SecurityUtilExt;
import com.senlingspace.payment.douyin.DouyinHttpClient;
import com.senlingspace.payment.douyin.bean.request.DouyinProductRequest;
import com.senlingspace.payment.douyin.bean.request.DouyinShopQueryRequest;
import com.senlingspace.payment.douyin.bean.response.DouyinProductResponse;
import com.senlingspace.payment.douyin.bean.response.DouyinShopQueryResponse;
import com.senlingspace.payment.douyin.service.DouYinProductService;
import com.senlingspace.payment.douyin.service.DouYinShopService;
import com.senlingspace.system.domain.SlkjShop;
import com.senlingspace.system.domain.dto.ShopProjectDTO;
import com.senlingspace.system.domain.vo.PosProjectVo;
import com.senlingspace.system.service.IProjectService;
import com.senlingspace.system.service.ISlkjFareSchemeService;
import com.senlingspace.system.service.ISlkjShopService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.ZoneOffset;
import java.util.*;



@Slf4j
@AllArgsConstructor
@Service
public class DouYinProductServiceImpl implements DouYinProductService {


    private final IProjectService projectService;
    private final ISlkjFareSchemeService iSlkjFareSchemeService;
    private final ISlkjShopService slkjShopService;
    private final DouYinShopService douYinShopService;

    /**
     * 创建修改抖音商品接口
     * 获取创建抖音所需要的数据
     * */
    @Override
    public ArrayList<DouyinProductResponse> create(Long shopId) throws ServiceException {

        ArrayList<DouyinProductResponse> result = new ArrayList<>();

        //        获取数据库项目信息
        ShopProjectDTO shopProject = projectService.getShopAndProjectDetails(shopId);
        if (shopProject == null) {
            log.error("无法同步门票信息 获取数据库项目信息为空");
            throw new ServiceException("无法同步门票信息 获取数据库项目信息为空 shopId"+ shopId);
        }

        //        获取数据库票价信息
        AjaxResult projects = iSlkjFareSchemeService.projects(shopId, OrderSource.DOUYIN.getCode());
        log.info("获取抖音价格信息：{}", JSON.toJSONString(projects));
        Integer code = (Integer) projects.get("code");
        if (200 != code) {
            log.error("获取抖音价格信息失败：{}", JSON.toJSONString(projects));
            throw new ServiceException(String.format("获取抖音价格信息失败：%s", JSON.toJSONString(projects)));
        }
        JSONObject jsonObject = new JSONObject(projects);
        String data = jsonObject.getString("data");
        PosProjectVo projectVo = JSON.parseObject(data, PosProjectVo.class);

        //       获取门店详细数据
        SlkjShop slkjShop = slkjShopService.selectSlkjShopByShopId(shopId);
        if (slkjShop == null) {
            log.error("无法同步门票信息 获取数据库商店信息为空");
            throw new ServiceException("无法同步门票信息 获取数据库商店信息为空");
        }

        //      获取抖音门店信息
        DouyinShopQueryRequest douyinShopQueryRequest = new DouyinShopQueryRequest();
        douyinShopQueryRequest.setAccountId(slkjShop.getAccountId());
        DouyinShopQueryResponse douyinShopQueryResponse = douYinShopService.prepare(douyinShopQueryRequest);

        if (douyinShopQueryResponse.getExtra().getErrorCode() != 0) {
            log.error("获取抖音门店信息异常: {}", JSON.toJSONString(douyinShopQueryRequest));
            throw new ServiceException(String.format("获取抖音门店信息异常: %s", JSON.toJSONString(douyinShopQueryRequest)));
        }

        List<PosProjectVo.Ticket> ticketDetails = projectVo.getTicketDetails();
        for (PosProjectVo.Ticket ticketDetail : ticketDetails) {
            List<PosProjectVo.Category> categories = ticketDetail.getCategories();
            for (PosProjectVo.Category category : categories) {
                DouyinProductResponse douyinProduct = createDouyinProduct(shopProject, category, slkjShop, douyinShopQueryResponse);
                result.add(douyinProduct);
            }
        }


        return result;
    }


    /**
     * 根据获取的数据封装抖音商品创建模板
     *
     * */
    private DouyinProductResponse createDouyinProduct(ShopProjectDTO shopProject, PosProjectVo.Category category, SlkjShop slkjShop, DouyinShopQueryResponse douyinShopQueryResponse) {

//        项目名
        String projectName = shopProject.getProjectName();
        String categoryName = category.getCategoryName();//票类名称
//        原价
        String originalPrice = category.getOriginalPrice();
        // 获取票价
        String douyinPrice = category.getDouyinPrice();
        // 内含门票数量
        Integer quantity = category.getQuantity();
        // 获取票类目ID
        Long fareSchemeDetailId = category.getFareSchemeDetailId();
        Long projectId = shopProject.getProjectId();
        String outId = projectId+ ","+fareSchemeDetailId ;//外部商品Id
        // 获取票类目名称
        String ticketCategoryName = category.getCategoryName();
        //        这里抖音给了数组结构，但是并不知道如果多个门店对应的是数组中的哪个，只能暂时写死一个
        String accountName = douyinShopQueryResponse.getData().getPois().get(0).getRootAccount().getAccountName();
        //      抖音门店ID
        String poiId = douyinShopQueryResponse.getData().getPois().get(0).getPoi().getPoiId();
        // accountId
        String accountId = douyinShopQueryResponse.getData().getPois().get(0).getRootAccount().getAccountId();
        if (StringUtils.isBlank(category.getPlatformImageUrl())) {
            log.error("无法获取门票信息 获取数据库抖音图片信息为空，票类编号：{}",outId);
            throw new ServiceException("无法获取门票信息 获取数据库图片信息为空，票类编号："+outId);
        }

        String[] imageUrlArray = category.getPlatformImageUrl().split(","); // 将字符串按逗号分割，图片列表
        StringBuffer imageUrlStr = new StringBuffer();
        imageUrlStr.append("[");
        for (String img_url : imageUrlArray) {
            imageUrlStr.append("{\"url\":\""+ img_url + "\"},");
        }
        imageUrlStr.deleteCharAt(imageUrlStr.length()-1);
        imageUrlStr.append("]");//封面图


        //      封装抖音创建更新商品请求体
        DouyinProductRequest request = new DouyinProductRequest();

        // 创建Product对象并设置字段
        DouyinProductRequest.Product product = new DouyinProductRequest.Product();

        product.setOutId(outId);

        product.setAccountName(accountName);
        product.setBizLine(1);  // 业务线
        product.setCategoryId(4017001L);  // 三级品类ID
        product.setProductName(categoryName);  // 商品名
        product.setProductType(1);  // 商品类型
        product.setSoldStartTime(shopProject.getStartDate().atStartOfDay().toEpochSecond(ZoneOffset.UTC));  // 售卖开始时间(抖音要求为秒时间戳)
        product.setSoldEndTime(shopProject.getEndDate().atStartOfDay().toEpochSecond(ZoneOffset.UTC));  // 售卖结束时间
        request.setAccountId(accountId);// 设置商家ID

        // 店铺信息
        DouyinProductRequest.Poi poi = new DouyinProductRequest.Poi();
        poi.setPoiId(poiId);  // poiID
        product.setPois(Arrays.asList(poi));

        // 设置 attr_key_value_map
        Map<String, String> attrMap = new HashMap<>();
        attrMap.put("appointment", "{\"need_appointment\":false, \"ahead_time_type\":0, \"ahead_hour_num\":5, \"external_link\":\"urlxxx\", \"order_appointment_time_url\":\"urlxxx\"}");
        attrMap.put("auto_renew", "true");
        attrMap.put("bring_out_meal", "false");

//        todo 指定不可使用的日期开关；指定周几不可用；指定节假日不可用；指定日期不可用；节假日具体日期
        attrMap.put("can_no_use_date", "{\"enable\": false, \"days_of_week\": [7, 1, 2, 3, 4], \"holidays\": [1, 2, 3, 4, 5], \"date_list\": [\"2022-03-08\", \"2022-03-09\"], \"holiday_dates\": {\"1\": \"2022.01.01-2022.01.03\"}}");
//        attrMap.put("description_rich_text", "[{\"note_type\": 1, \"content\": \"其他说明信息-门票\"}]");

        attrMap.put("image_list", imageUrlStr.toString());
//        全天/仅指定时间可用；时间段（比如12:-14:）
        attrMap.put("use_time", "{\"use_time_type\":1}");
        attrMap.put("use_date", "{\"use_date_type\":1,\"use_start_date\":\"" + shopProject.getStartDate() + "\",\"use_end_date\":\"" + shopProject.getEndDate() + "\"}");

        attrMap.put("show_channel", "1");
        attrMap.put("RefundPolicy", "1");
//        attrMap.put("Description", "[\""+shopProject.getInstructions()+"\"]");
        attrMap.put("Description", "[\"\"]");
        attrMap.put("refund_need_merchant_confirm", "true");//"退款是否需商家审核"
        attrMap.put("Notification", "[{\"title\":\"标题\",\"content\":\"" + shopProject.getProjectName() + "\"}]");

//        attrMap.put("rec_person_num", "10");
//        attrMap.put("rec_person_num_max", "50");
        product.setAttrKeyValueMap(attrMap);


        //        商品额外信息
        DouyinProductRequest.ProductExt productExt = new DouyinProductRequest.ProductExt();
        productExt.setAutoOnline(true);//审核通过是否自动上架
////        标记商品为测试商品
//        DouyinProductRequest.TestExtra testExtra = new DouyinProductRequest.TestExtra();
//        testExtra.setTestFlag(true);
//        ArrayList<String> uids = new ArrayList<>();
//        uids.add("104501191705");//测试商品可以看到的账号列表
//        uids.add("7559933816");//测试商品可以看到的账号列表
//        uids.add("24148734127");//测试商品可以看到的账号列表
//        testExtra.setUids(uids);
//        productExt.setTestExtra(testExtra);
        product.setProductExt(productExt);

        request.setProduct(product);

// 创建SkuStruct对象并设置字段
        DouyinProductRequest.SkuStruct sku = new DouyinProductRequest.SkuStruct();
        // 实际支付价格，单位：分
        sku.setActualAmount(Integer.valueOf(douyinPrice));
//        顾客实际支付金额须低于116.82元(折扣率不得低于1%)
        sku.setOriginAmount(Integer.valueOf(originalPrice));  // 原价，单位：分
        sku.setSkuName(ticketCategoryName);  // SKU 名称
        sku.setStatus(1);  // 状态，1 为在线

// 库存信息
        DouyinProductRequest.StockStruct stock = new DouyinProductRequest.StockStruct();
        stock.setLimitType(1);  // 库存上限类型，1：有限库存 2：无限库存
        stock.setStockQty(40);  // 总库存数量
        sku.setStock(stock);

// 设置 sku 的 attr_key_value_map
        Map<String, String> skuAttrMap = new HashMap<>();
        skuAttrMap.put("code_source_type", "1");//1-抖音码 2-三方码 3-预导码
        skuAttrMap.put("commodity", "[{\"group_name\":\"" + ticketCategoryName + "\",\"total_count\":1,\"option_count\":1,\"item_list\":[{\"name\":\"门票\",\"price\":"
                + originalPrice + ",\"count\":" + quantity + ",\"unit\":\"张\"}]}]");
        skuAttrMap.put("limit_rule", "{\"is_limit\":false,\"total_buy_num\":5}");
        skuAttrMap.put("settle_type", "1");
        skuAttrMap.put("use_type", "1");//1-到店核销
        sku.setAttrKeyValueMap(skuAttrMap);
        request.setSku(sku);

// 打印封装好的请求体
        log.info("抖音创建商品请求体：{}", JSON.toJSONString(request));
        DouyinProductResponse invoke = DouyinHttpClient.invoke(request);
        return invoke;
    }


}
